package rents.internal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import rents.AccountContribution;
import rents.RentConfirmation;
import rents.RentNetwork;
import rents.User;
import rents.internal.account.Account;
import rents.internal.account.AccountRepository;
import rents.internal.local.Local;
import rents.internal.local.LocalRepository;
import rents.internal.rent.RentRepository;

import common.money.MonetaryAmount;

@Service("rentNetwork")
public class RentNetworkImpl implements RentNetwork{
	
	private AccountRepository accountRepository;

	private LocalRepository localRepository;

	private RentRepository rentRepository;
	
	@Autowired
	public RentNetworkImpl(AccountRepository accountRepository, LocalRepository localRepository,
			RentRepository rentRepository) {
		this.accountRepository = accountRepository;
		this.localRepository = localRepository;
		this.rentRepository = rentRepository;
	}

	@Transactional
	public RentConfirmation rentAccountFor(User user) {
		Account account = accountRepository.findByCreditCard(user.getCreditCardNumber());
		Local local = localRepository.findByMerchantNumber(user.getMerchantNumber());
		MonetaryAmount amount = local.calculateBenefitFor(account, user);
		AccountContribution contribution = account.makeContribution(amount);
		return rentRepository.confirmRent(contribution, user);
	}

}
